"""
This file is part of GSBEdit. For copyright and licensing information, please
see gsbedit.py in the GSBEdit base directory.
"""


import os
import os.path
import ConfigParser
import sys

import game_data.mod as gdm
import game_data.package as package


class GSBInstall:
    def __init__(self, base):
        self.base = base
        
        self.get_packages()
        
        core_package = self.get_package('gsb_base')
        core_mod = gdm.Mod('', core_package, self.make_path(['data']))
        
        self.mods = {'gsb_base' : core_mod}
        self.mod_lookup_by_friendly_name = {core_mod.get_friendly_name() : 'gsb_base'}
        
        self.current_mod = 'gsb_base'
    
    
    def get_packages(self):
        self.packages = {}
        package_dir = self.make_path(['data', 'packages'])
        for package_file in os.listdir(package_dir):
            full_path = self.make_path(['data', 'packages', package_file])
            if not(os.path.isfile(full_path)):
                continue
            try:
                p = package.Package(full_path)
            except:
                print >> sys.stderr, "Invalid package file: %s" % full_path
                continue
            
            self.packages[p.get_internal_name()] = p
    
    
    def make_path(self, path):
        return os.path.join(self.base, *path)
    
    
    def find_mods(self):
        mod_dirs = []
        mod_reg_dir = self.make_path(['data', 'installs'])
        print 'Scanning "%s" for install files.' % self.base
        
        if not(os.path.exists(mod_reg_dir)):
            print " - Unable to find 'installs' directory"
            
            if os.path.exists(self.make_path(['data', 'modules'])):
                print " - Fell back to 'modules' detection - success. However, no mods will be loaded."
                return True
                
            return False

        # Run through the mods that GSB has been told about
        for mod_reg_file in os.listdir(mod_reg_dir):
            print " - Attempting to resolve '%s'" % mod_reg_file
            filename = os.path.join(mod_reg_dir, mod_reg_file)
            mod = ConfigParser.ConfigParser()
            mod.read(filename)
            
            # If it's valid then add it to our list
            if mod.has_option('config', 'path'):
                mod_dir = mod.get('config', 'path')

                if not(os.path.exists(self.make_path([mod_dir]))):
                    print " --- install file '%s' points to invalid mod directory" % mod_reg_file
                
                package = self.get_package(mod_reg_file.replace('.txt', ''))
                if package == None:
                    continue
                mod_dirs.append((mod_dir, package))
                self.mod_lookup_by_friendly_name[package.get_name()] = mod_dir

            else:
                print " - Invalid install file: %s" % mod_reg_file

        for mod_dir, package in mod_dirs:
            try:
                self.mods[mod_dir] = gdm.Mod(mod_dir, package, self.make_path([mod_dir, 'data']))
            except:
                print " - Failed to create Mod '%s'" % mod_dir
        
        return True
    
    
    def get_value_from_package(self, filename, section, key):
        value = None
        package = ConfigParser.ConfigParser()
        package.read(filename)
        if package.has_option(section, key):
            value = package.get(section, key).strip('"')
        return value
    
    
    def get_package(self, mod_name):
        package_name     = mod_name
        package_name_alt = 'gsb_%s' % mod_name
        
        if package_name in self.packages:                
            return self.packages[package_name]
        elif package_name_alt in self.packages:
            return self.packages[package_name_alt]
        else:
            print " --- Unable to find matching package file."
            return None
        
        
    #def get_friendly_name(self, mod_name):
    #    package = self.get_package(mod_name)
    #    
    #    if package == None:
    #        return mod_name.title()
    #    else:
    #        return package.get_name()
    
    
    def get_mod_list(self):
        return sorted(self.mods.keys())
    
    def get_mod_list_friendly(self):
        return sorted([x.get_friendly_name() for x in self.mods.values()])
    
    
    def get_mod(self, name):
        return self.mods[name]
    
    
    def get_mod_by_friendly_name(self, name):
        internal_name = self.mod_lookup_by_friendly_name[name]
        return self.get_mod(internal_name)
    
    
    def set_current_mod(self, name):
        self.current_mod = name
    
    
    def set_current_mod_by_friendly_name(self, name):
        internal_name = self.mod_lookup_by_friendly_name[name]
        self.set_current_mod(internal_name)
    
    
    def get_current_mod(self):
        return self.get_mod(self.current_mod)
    
